package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketUser;
import com.cskaoyan.market.service.UserService;
import com.cskaoyan.market.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName WxAuthController
 * @Description: TODO
 * @Author 远志 zhangsong@cskaoyan.onaliyun.com
 * @Date 2024/3/28 9:48
 * @Version V1.0
 **/
@RestController
@RequestMapping("wx/auth")
public class WxAuthController {

    @Autowired
    UserService userService;

    @Autowired
    SecurityManager securityManager;


    @PostMapping("login")
    public Object login(@RequestBody Map<String, String> params){
        String username = params.get("username");
        String password = params.get("password");
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            //todo
            return ResponseUtil.badArgument();
        }
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseUtil.wrongUsernameOrPassword();
        }
        //认证成功之后，需要取出principle
        MarketUser user = (MarketUser) subject.getPrincipal();
        //使用的是shiro提供的session
        Session session = subject.getSession();
        session.setAttribute("user", user);
//        MarketUser user = userService.login(username, password);
//        if(user == null){
//            return ResponseUtil.wrongUsernameOrPassword();
//        }
        Map<String, Object> data = new HashMap<>();
        Map<String, String> userInfo = new HashMap<>();
        userInfo.put("avatarUrl", user.getAvatar());
        userInfo.put("nickName", user.getUsername());
        //token其实服务器开辟的一块内存空间的编号，session编号
        Serializable id = session.getId();
        //我们就把session的编号以响应体中token的字段形式返回给了客户端
        //客户端会接收位于此处的token的值，下一次访问时，会将token的值放置在X-CskaoyanMarket-Token请求头中
        //下一次我们主动获取这个请求头的值，那么便可以获取之前session的编号
        //为什么需要这么麻烦呢？原因在于小程序不会携带Cookie:JSESSIONID=XXXX
        data.put("token", id);
        data.put("userInfo", userInfo);
        return ResponseUtil.ok(data);
    }
}
